package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	pkgConfig "github.com/ChuranNeko/gginx/pkg/config"
	"github.com/ChuranNeko/gginx/pkg/engine"
)

func main() {
	// 加载配置文件
	conf, err := pkgConfig.LoadConfig("config.yaml")
	if err != nil {
		log.Fatalf("加载配置文件失败: %v", err)
	}

	// 转换配置类型
	engineConfig := &engine.Config{
		Balancer: &engine.BalancerConfig{
			Strategy: conf.Proxy.Strategy,
			Backends: conf.Proxy.Backends,
		},
	}

	// 创建代理引擎
	proxyEngine, err := engine.NewProxyEngine(engineConfig)
	if err != nil {
		log.Fatalf("创建代理引擎失败: %v", err)
	}

	// 设置服务器配置
	server := &http.Server{
		Addr:           fmt.Sprintf(":%d", conf.Server.Port),
		Handler:        proxyEngine,
		ReadTimeout:    conf.Server.ReadTimeout,
		WriteTimeout:   conf.Server.WriteTimeout,
		MaxHeaderBytes: conf.Server.MaxHeaderBytes,
	}

	// 启动健康检查
	go proxyEngine.StartHealthCheck(conf.Health.Interval, conf.Health.Timeout)

	// 启动服务器
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("服务器启动失败: %v", err)
		}
	}()

	// 等待信号退出
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	<-sigCh

	// 优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		log.Printf("服务器关闭出错: %v", err)
	}
}
